package com.example.demo2.dao;

import com.example.demo2.pojo.Department;
import com.example.demo2.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

//商品dao
@Repository
public class Productdao {
    //模拟数据库中的数据
    private static Map<Integer, Product> ProductMap =null;
    //商品有所属的商品种类
    @Autowired
    private Departmentdao departmentdao;

    static {
        ProductMap =new HashMap<Integer,Product>();//创建一个商品表
        ProductMap.put(101,new Product(101,"苹果",10,12,"斤","2021-1-1",new Department(101,"水果")));
        ProductMap.put(102,new Product(102,"土豆",10,20,"斤","2021-1-1",new Department(102,"蔬菜")));
        ProductMap.put(103,new Product(103,"伊利纯牛奶",10,30,"箱","2021-1-1",new Department(103,"牛奶")));
        ProductMap.put(104,new Product(104,"可口可乐",10,1,"瓶","2021-1-1",new Department(104,"饮料")));
    }
    //主键自增
    private static Integer initId=105;
    //增加一个商品,product是已经设置好的参数，还没有给id
    public void save(Product product){
        if (product.getId()==null){
            product.setId(initId++);
        }
        product.setDepartment(departmentdao.getDepartmentById(product.getDepartment().getId()));
        //放入商品表
        ProductMap.put(product.getId(),product);

    }

    //获取所有商品表信息
    public Collection<Product> getProducts(){
        return ProductMap.values();
    }
    //通过id得到信息
    public static Product getProductById(Integer id){
        return ProductMap.get(id);
    }
    //通过id删除商品信息
    public void deleteById(Integer id){
        ProductMap.remove(id);
    }
}
